package com.changgou.seckill.mq;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.pojo.SeckillStatus;
import com.changgou.seckill.service.SeckillOrderService;
import com.changgou.util.IdWorker;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/*****
 * @Author: 黑马训练营
 * @Description: com.changgou.seckill.mq
 ****/
@Component
@RabbitListener(queues = {"queueSeckillOrder"})
public class SeckillOrderStatusListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    /****
     * 秒杀订单支付状态监听
     */
    @RabbitHandler
    public void getPayStatus(String message){
        System.out.println("message:"+message);
        Map<String,String> resultMap = JSON.parseObject(message,Map.class);

        //通信标识return_code=SUCCESS
        String return_code = resultMap.get("return_code");

        if(return_code.equals("SUCCESS")){
            //业务结果result_code=SUCCESS
            String result_code = resultMap.get("result_code");

            //修改指定订单的状态，必须知道username "SeckillStatus_"+username
            //订单 必须知道username,redisTemplate.boundHashOps("SeckillOrder").put(seckillStatus.getUsername(),seckillOrder);
            //从attach附加参数中获取用户名
            Map<String,String> attachMap = JSON.parseObject(resultMap.get("attach"),Map.class);

            if(result_code.equals("SUCCESS")){
                //微信支付交易流水号transaction_id
                String transactionid =resultMap.get("transaction_id");
                //用户支付成功，修改订单状态
                seckillOrderService.updatePayStatus(attachMap.get("username"),transactionid);
            }else{
                //支付失败，删除订单(真删了),回滚数据库(Redis|MySQL)数据
                seckillOrderService.closeOrder(attachMap.get("username"));
            }
        }
    }

}
